// pages/article/video/index.js
const {
  decodeUserInfo
} = require('../../../api/login')
const {
  filterObj,
  timeago,
  pxTorpx
} = require('../../../utils/util')
const {
  browseList,
  collectCourse,
  courseItemList,
  articleList,
  courseDetail,
  couponUseList,
  coursePay
} = require('../../../api/api')
const {checkLogin} = require("../../../utils/util");

function anonymous(val) {
  var nickname = ''
  const isValidPhone = /^[1]([3-9])[0-9]{9}$/.test(val);
  if (isValidPhone) {
    nickname = val.substring(0, 3) + '****' + val.substring(7, 11)
  } else {
    nickname = val
  }
  return nickname
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    couponTitle: '可用优惠券',
    couponContent: '你有一张优惠券可用',
    couponVisible: false,
    url: '',
    title: '充值提示',
    content: "非会员只能看前30秒的内容",
    visible: false,
    isVip: false,
    bottomLift: getApp().globalData.bottomLift,
    tabList: ['课程目录', '课程简介', '参与人数'],
    tabIndex: 0,
    keyOptions: ['考前准备', '高考知识'],
    courseList: [],
    userList: [{}, {}, {}],
    isPlay: false,
    isPause: true,
    coursePageNo: 1,
    coursePageSize: 20,
    browsePageNo: 1,
    browsePageSize: 20,
    courseId: 1,
    ellipsis: false,
    browseTotal: 0,
    isBuyed: false,
    currentTime: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.fetchUserInfo()
    if (options.params) {
      const params = JSON.parse(decodeURIComponent(options.params))
      this.setData({
        courseId: params.id
      })
      this.getCourseDetail()
      this.getCourseList()
      this.getBrowseList()
      wx.setNavigationBarTitle({
        title: params.title,
      })
    }
    if (options.videoPath) {
      this.setData({
        url: options.videoPath
      })
      wx.setNavigationBarTitle({
        title: options.title,
      })
    }
  },
  async getCourseDetail() {
    const {
      courseId,
      catalogId
    } = this.data
    var params = {
      itemId: catalogId,
      id: courseId
    }
    params = filterObj(params)
    var {
      result
    } = await courseDetail(params)
    if (result.labelTag) {
      result['labelTagOptions'] = result.labelTag.split(',')
    }
    this.setData({
      details: result,
      isBuyed: result.isBuyed,
      catalog: result.courseList,
      catalogId: result.courseList.id
    })
  },

  async getCourseList() {
    const {
      coursePageNo,
      coursePageSize,
      courseId
    } = this.data
    const params = {
      pageNo: coursePageNo,
      pageSize: coursePageSize,
      courseId: courseId
    }
    const {
      result
    } = await courseItemList(params)
    this.setData({
      ['courseList[' + (coursePageNo - 1) + ']']: result.records,
      coursePageNo: coursePageNo + 1,
    })
  },
  async getBrowseList() {
    const {
      browsePageNo,
      browsePageSize,
      courseId,
    } = this.data
    const params = {
      pageNo: browsePageNo,
      pageSize: browsePageSize,
      courseId: courseId
    }
    const {
      result
    } = await browseList(params)
    if (result.records.length == 0) return
    result.records.map((item) => {
      item.nickname = anonymous(item.nickname)
      item.createTime = timeago(item.createTime)
    })
    this.setData({
      ['browseList[' + (browsePageNo - 1) + ']']: result.records,
      browsePageNo: browsePageNo + 1,
      browseTotal: result.total
    })
  },
  ellipsis() {
    this.setData({
      ellipsis: !this.data.ellipsis
    })
  },
  async collect(e) {
    const {
      collect
    } = e.currentTarget.dataset
    const {
      courseId,
      details
    } = this.data
    const result = await collectCourse(courseId)
    wx.showToast({
      title: result.message,
      icon: 'none'
    })
    details.isCollection = !collect
    this.setData({
      details
    })
  },
  async pay() {
    var {
      money
    } = this.data.details
    const {
      result
    } = await couponUseList(money)
    if (result.length > 0) {
      this.setData({
        couponVisible: true,
        couponList: result,
        couponContent: '您有' + result.length + '张优惠券可用'
      })
    } else {
      this.doWxPay()
    }
  },
  async doWxPay(couponId) {
    const params = {
      courseId: this.data.courseId
    }
    if (couponId) {
      params.couponId = couponId
    }
    const {
      result
    } = await coursePay(params)
    const _this = this
    wx.requestPayment({
      nonceStr: result.nonceStr,
      package: result.package,
      paySign: result.paySign,
      timeStamp: result.timeStamp,
      signType: result.signType,
      success: async function (res) {
        wx.showToast({
          icon: 'success',
          title: '购买成功',
        })
      },
      fail: function (res) {

      }
    })
  },
  confirm(e) {
    const couponId = e.detail
    this.doWxPay(couponId)
  },
  async changeCatalog(e) {
    const {
      id,
      value
    } = e.currentTarget.dataset
    if (id == this.data.catalogId) return
    wx.showLoading({
      title: '加载中'
    })

    this.setData({
      catalog: value,
      catalogId: id
    })
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    }
    wx.hideLoading()
    var params = {
      itemId: id,
      id: this.data.courseId
    }
    params = filterObj(params)
    var {
      result
    } = await courseDetail(params)
  },
  changeIndex(e) {
    const {
      index
    } = e.currentTarget.dataset
    const {
      browseTotal
    } = this.data
    this.setData({
      tabIndex: parseInt(index)
    })
    //
    if (index == 2) {
      var that = this
      const query = wx.createSelectorQuery();
      query.selectAll('.user_item').fields({
        size: true,
      }).exec(function (res) {
        var list = res[0]
        var height = 0
        var total = browseTotal > 10 ? 10 : browseTotal
        for (var i = 0; i < total; i++) {
          height = height + list[i].height
        }
        var gapHeight = browseTotal > 10 ? 504 : 56 * browseTotal
        var itemHeight = pxTorpx(height)
        that.setData({
          courseJoinsBoxHeight: itemHeight + gapHeight
        })
      })
    }
  },
  playVideo() {
    var {
      currentTime,
      isVip,
      isBuyed,
      details
    } = this.data
    checkLogin().then(res=>{
      if (currentTime >= 30 && (!isVip && !isBuyed) && details.payType == 1) {
        this.setData({
          visible: true,
          isPlay: false
        })
        return
        
      }
      this.videoContext.play();
      this.setData({
        isPlay: true,
        isPause: true
      })
    }).catch(e=>{
      if (currentTime >= 30){
        this.setData({
          isPlay: false,
          visible: true,
          title:'是否跳转至登录页',
          content:'需要您登录后，才能获取其中的内容',
        })
      }
    })
  },
  pauseVideo() {
    this.videoContext.pause();
    this.setData({
      isPlay: false,
      isPause: true
    })
  },
  endVideo() {
    this.setData({
      isPlay: false,
      isPause: true
    })
  },
  timeUpdate: function (e) {
    //实时播放进度 秒数
    const {
      isVip,
      vipType,
      isBuyed,
      details
    } = this.data
    var currentTime = e.detail.currentTime
    this.setData({
      isPlay: true,
      isPause: true,
      currentTime
    })
    checkLogin().then(res=>{
      if (currentTime >= 30 && (!isVip && !isBuyed) && details.payType == 1) {
        this.videoContext.pause();
        this.videoContext.exitFullScreen()
        this.setData({
          visible: true,
          isPlay: false
        })
      }
    }).catch(e=>{
        if (currentTime >= 30){
          this.videoContext.pause();
          this.videoContext.exitFullScreen()
          this.setData({
            isPlay: false,
            visible: true,
            title:'是否跳转至登录页',
            content:'需要您登录后，才能获取其中的内容',
          })
        }
    })
 
  },
  goto() {
    wx.navigateTo({
      url: '/pages/volunteer/index/index',
    })
  },
  cancel() {
    wx.navigateBack({
      delta: 1
    })
  },
  confirm() {
    checkLogin().then(res=>{
      wx.navigateTo({
        url: '/pages/article/vip/index',
      })
    }).catch(e=>{
      wx.navigateTo({
        url: '/pages/login/index',
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.videoContext = wx.createVideoContext('myVideo')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
    async fetchUserInfo() {
      const {
        result
      } = await decodeUserInfo()
      this.setData({
        isVip: result.vips.length > 0 ? true : false,
        isSvip: result.vips.indexOf('svip') > -1 ? true : false,
      })
    },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const {
      tabIndex
    } = this.data
    const {
      courseList,
      coursePageSize,
      browsePageSize,
      browseList,
      ellipsis
    } = this.data
    if (tabIndex == 1) {
      let count = courseList.length - 1
      if (courseList[count].length < coursePageSize) {
        return
      }
      this.getCourseList()
    } else if (tabIndex == 2) {
      let count = browseList.length - 1
      if (browseList[count].length < browsePageSize && !ellipsis) {
        return
      }
      this.getBrowseList()
    }


  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const {
      details
    } = this.data
    return {
      title: details.title,
      imageUrl: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg',
      path: `/pages/article/video/index?params=` + encodeURIComponent(JSON.stringify(details))
    }
  }
})
